package com.hmyd.hmyd_android.ui;

import java.io.File;
import java.text.NumberFormat;
import java.util.List;

import General.CropPic.PhotoGraph;
import General.CropPic.Listener.CropListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.commons.Constants;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.ChangeNicknameDialog;
import com.hmyd.hmyd_android.dialog.ChangeNicknameDialogListener;
import com.hmyd.hmyd_android.dto.Avatar;
import com.hmyd.hmyd_android.dto.GetPushInfo;
import com.hmyd.hmyd_android.dto.SinaDetail;
import com.hmyd.hmyd_android.dto.User;
import com.hmyd.hmyd_android.easydialog.EasyDialog;
import com.hmyd.hmyd_android.fragment.AssetsFragment;
import com.hmyd.hmyd_android.fragment.InvestmentBillFragment;
import com.hmyd.hmyd_android.fragment.InvestmentFragment;
import com.hmyd.hmyd_android.fragment.MoreFragment;
import com.hmyd.hmyd_android.fragment.RecommendationFragment;
import com.hmyd.hmyd_android.shop.JfMallActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.PreferencesUtils;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.LockPatternUtils;
import com.hmyd.hmyd_android.view.LockPatternView;
import com.hmyd.hmyd_android.view.LockPatternView.Cell;
import com.hmyd.hmyd_android.view.RoundImageView;
import com.hmyd.hmyd_android.view.listview.XListView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapCommonUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 主视图页面
 * 
 * @author sun_t
 * 
 */
@ContentView(R.layout.layout_main)
public class MainActivity extends BasicFragmentActivity implements View.OnClickListener,
CropListener {
	private final int USERINFO = 2;
	private final int LOGIN = 3;
	private final int LOGINOUT = 0;
	private final int CHANGEAVATAR = 1;
	private final int CHANGENICKNAME = 4;
	private final int REQUEST_CODE_Gesturepwd_Unlock_Forget = 5;
	private final int SINA_ACCOUNT = 6;
	private final int GET_PUSH_INFO =7;

	private RecommendationFragment recommendationFragment;
	private InvestmentBillFragment investmentBillFragment;
	private InvestmentFragment investmentFragment;
	private AssetsFragment assetsFragment;
	private MoreFragment moreFragment;

	@ViewInject(R.id.home_tab_recommendation_layout)
	private View mHomeTabRecommendationLayout;
	@ViewInject(R.id.home_tab_investment_layout)
	private View mHomeTabInvestmentLayout;
	@ViewInject(R.id.home_tab_assets_layout)
	private View mHomeTabAssetsLayout;
	@ViewInject(R.id.home_tab_more_layout)
	private View mHomeTabMoreLayout;

	private static int[] imgIds = {
			R.id.home_tab_recommendation_image, 
			R.id.home_tab_investment_image, 
			R.id.home_tab_assets_image,
			R.id.home_tab_more_image	
	};

	private static int[] txtIds = {
			R.id.home_tab_recommendation_text,
			R.id.home_tab_investment_text,
			R.id.home_tab_assets_text,
			R.id.home_tab_more_text
	};

	private FragmentManager mFragmentManager;

	// fragment 相对应的正常icon
	private int iconNormal[] = { R.drawable.ind_tui_up, R.drawable.ind_tou_up,
			R.drawable.ind_zi_up, R.drawable.ind_geng_up };
	// fragment 相对应的按压icon
	private int iconPressed[] = { R.drawable.ind_tui_dow, R.drawable.ind_tou_dow,
			R.drawable.ind_zi_dow, R.drawable.ind_geng_dow };
	// fragment 相对应的标题
	//private int investmentHead = R.layout.investment_head;
	private String titleArray[] = { "惠民推荐", "我要投资", "我的资产", "更多" };
	private String toWhere;

	@ViewInject(R.id.main_home_title)
	private View home_title;
	@ViewInject(R.id.main_title)
	private TextView home_title_string;
	@ViewInject(R.id.title_logo)
	private ImageView titleLogo;
	@ViewInject(R.id.home_right)
	private ImageView home_right;
	@ViewInject(R.id.home_left)
	private ImageView home_left;
	@ViewInject(R.id.realtabcontent)
	private FrameLayout realtabcontent;

	// 侧滑栏个人信息
	@ViewInject(R.id.sidemenu)
	private RelativeLayout mSideLayout;
	@ViewInject(R.id.id_menu)
	private DrawerLayout mDrawerLayout;
	@ViewInject(R.id.mainContent)
	private RelativeLayout mMainContent;
//	@ViewInject(R.id.tv_score)
//	private TextView mTvScore;// 我的积分
//	@ViewInject(R.id.tv_score_fen)
//	private TextView tv_score_fen;
	@ViewInject(R.id.messages)
	private TextView mTvMessages;// 未读消息数目
	@ViewInject(R.id.tv_security)
	private TextView mTvSecurity;// 安全等级
	@ViewInject(R.id.tv_security_string)
	private TextView tv_security_string;
	@ViewInject(R.id.side_layout_unlogin)
	private LinearLayout unLoginLayout;
	@ViewInject(R.id.side_layout_login)
	// 登陆
	private RelativeLayout loginLayout;
	@ViewInject(R.id.tv_side_menu_name)
	private TextView mTvName;// 用户名
	@ViewInject(R.id.tv_investment_code)
	private TextView mTvInvestmentCode;// 邀请码
	@ViewInject(R.id.ge_icon_ewm)
	private ImageView mGe_icon_ewm;	//二维码
	@ViewInject(R.id.icon)
	private RoundImageView icon;// 头像
	@ViewInject(R.id.side_btn_logout)
	private Button mBtnLogout;// 退出登录
	private PhotoGraph mPhotoGraph;
	@ViewInject(R.id.side_layout_sina)
	private View side_layout_sina;


	private SharedPreferences sharedPreferences;
	private Editor editor;

	//会员中心
	@ViewInject(R.id.member_center)
	private RelativeLayout member_center;
	//会员等级图标
	@ViewInject(R.id.ge_icon_vip)
	private ImageView ge_icon_vip;
	@ViewInject(R.id.side_layout_gift)
	private RelativeLayout giftLayout;
	@ViewInject(R.id.side_layout_points)
	private RelativeLayout pointsLayout;
	@ViewInject(R.id.side_layout_shop)
	private RelativeLayout shopLayout;
	@ViewInject(R.id.side_layout_msg)
	private RelativeLayout msgLayout;
	@ViewInject(R.id.side_layout_frends)
	private RelativeLayout frendsLayout;
	@ViewInject(R.id.side_layout_security_center)
	private RelativeLayout securityLayout;
	@ViewInject(R.id.side_btn_logout)
	private Button logoutLayout;
	@ViewInject(R.id.side_btn_regedit)
	private Button mBtnRegedit;
	@ViewInject(R.id.side_btn_login)
	private Button mBtnLogin;
	// 新手指引
	@ViewInject(R.id.recommend_guide)
	private ScrollView recommendGuide;
	@ViewInject(R.id.assets_guide)
	private ImageView assetsGuide;

	@ViewInject(R.id.investmentLayot)
	private LinearLayout investmentLayot;

	@ViewInject(R.id.class_current_financial)
	private TextView class_current_financial;
	@ViewInject(R.id.regular_financial)
	private TextView regular_financial;
	@ViewInject(R.id.list)
	private XListView mList;

	// 手势解锁
	@ViewInject(R.id.gesture_password)
	private View mGesturePassword;
	@ViewInject(R.id.gesturepwd_unlock_lockview)
	private LockPatternView mLockPatternView;
	@ViewInject(R.id.gesturepwd_unlock_face)
	private ImageView mGesturepwdUnlockFace;
	@ViewInject(R.id.gesturepwd_unlock_forget)
	private View mGesturepwdUnlockForget;
	@ViewInject(R.id.gesturepwd_unlock_text)
	private TextView mHeadTextView;
	
	private	ImageView close;
	private ImageView birthday_push;
	private String tupian;

	private Animation mShakeAnim;
	private int mFailedPatternAttemptsSinceLastTimeout = 0;
	private CountDownTimer mCountdownTimer = null;
	private Handler mHandler = new Handler();

	private ActionBarDrawerToggle mDrawerToggle;

	public boolean isShow = false;
	
	private AlertDialog alertDialog;

	@SuppressLint({ "NewApi", "ResourceAsColor" })
	@OnClick({ R.id.icon, R.id.side_btn_login, R.id.side_btn_regedit, R.id.side_layout_gift,
		R.id.side_layout_points, R.id.side_layout_shop, R.id.side_layout_msg,
		R.id.side_layout_frends, R.id.side_layout_security_center, R.id.side_btn_logout,
		R.id.home_left, R.id.home_right, R.id.tv_investment_code, R.id.tv_side_menu_name,
		R.id.gesturepwd_unlock_forget, R.id.btn_guide_recommend, R.id.assets_guide,
		R.id.class_current_financial, R.id.regular_financial,R.id.member_center, 
		R.id.side_layout_sina, R.id.ge_icon_ewm })
	public void Click(View view) {
		switch (view.getId()) {
		case R.id.class_current_financial:
			class_current_financial.setBackground(getResources().getDrawable(R.drawable.near_btn_style));
			regular_financial.setBackground(getResources().getDrawable(R.drawable.benxiao2));
			class_current_financial.setTextColor(getResources().getColor(R.color.home_tab_text_pressed));
			regular_financial.setTextColor(getResources().getColor(R.color.home_tab_text_normal));

			AppBasic.isShow = false;
			setTabSelection(1);

			break;
		case R.id.regular_financial:
			class_current_financial.setBackground(getResources().getDrawable(R.drawable.near2));
			regular_financial.setBackground(getResources().getDrawable(R.drawable.benxiao));
			class_current_financial.setTextColor(getResources().getColor(R.color.home_tab_text_normal));
			regular_financial.setTextColor(getResources().getColor(R.color.home_tab_text_pressed));

			AppBasic.isShow = true;
			setTabSelection(1);
			break;
		case R.id.home_left:
			if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
				mDrawerLayout.closeDrawer(GravityCompat.START);
			} else {
				mDrawerLayout.openDrawer(GravityCompat.START);
			}
			break;
		case R.id.home_right:
			if (Utils.getSDKVersion() > 10) {
				showKFServer();
			} else {
				if (AppBasic.app != null && !TextUtils.isEmpty(AppBasic.app.serviceTel)) {
					Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
							+ AppBasic.app.serviceTel));
					startActivity(intent);
				} else {
					Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:400-969-1688"));
					startActivity(intent);
				}
			}
			break;
		case R.id.tv_side_menu_name:
			if (AppBasic.isCanUpdateNickname) {
				ChangeNicknameDialog changeNicknameDialog = new ChangeNicknameDialog(
						MainActivity.this, R.style.calculatorDialog,
						new ChangeNicknameDialogListener() {
							@Override
							public void getIdentifyind(String name) {
								RequestParams params = new RequestParams();
								params.addBodyParameter("nickname", name);
								onRequest(CHANGENICKNAME, UrlConstant.CHANGENICKNAME,
										HttpMethod.POST, params);
							}
						});

				changeNicknameDialog.show();
			} else {
				MyToast.showHMToast(MainActivity.this, false, "昵称只能修改一次");
			}

			break;
		case R.id.icon:
			if (AppBasic.isLogin) {
				mPhotoGraph = new PhotoGraph(MainActivity.this, this);
				mPhotoGraph.doPopup(R.id.id_menu);
			} else {
				startActivity(new Intent(MainActivity.this, LoginActivity.class));
			}
			break;
		case R.id.tv_investment_code:
			if (Utils.getSDKVersion() > 10) {
				ClipboardManager clip = (ClipboardManager) MainActivity.this
						.getSystemService(Context.CLIPBOARD_SERVICE);
				clip.setPrimaryClip(ClipData.newPlainText(null, AppBasic.urlToken));

				MyToast.showHMToast(MainActivity.this, true, "复制邀请码(" + AppBasic.urlToken + ")成功");
			}
			break;
		case R.id.ge_icon_ewm:
			startActivity(new Intent(MainActivity.this, InviteFriendActivity.class));
			break;
		case R.id.side_btn_login:
			startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class), LOGIN);
			break;
		case R.id.side_btn_regedit:
			startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
			break;
		case R.id.side_layout_gift:
			if (AppBasic.isLogin) {
				startActivity(new Intent(getApplicationContext(), GiftActivity.class));
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.member_center:
			if (!isFastDoubleClick()) {   // 添加防重复判断
				if (AppBasic.isLogin) {
					if (AppBasic.app != null && !TextUtils.isEmpty(AppBasic.app.memberLinkUrl)) {
						Utils.jumpURL(MainActivity.this, AppBasic.app.memberLinkUrl, "会员中心", "", false);
					}
				} else {
					startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
							LOGIN);
				}
			}
			break;
		case R.id.side_layout_points:
			if (AppBasic.isLogin) {
//				startActivity(new Intent(getApplicationContext(), MyScoreActivity.class));
				if (AppBasic.app != null && !TextUtils.isEmpty(AppBasic.app.myBill)) {
					Utils.jumpURL(MainActivity.this, AppBasic.app.myBill, "电子账单", "", false);
				}
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.side_layout_shop:
			if (AppBasic.isLogin) {
				startActivity(new Intent(getApplicationContext(), JfMallActivity.class));
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.side_layout_msg:
			if (AppBasic.isLogin) {
				startActivity(new Intent(getApplicationContext(), MessageListActivity.class));
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.side_layout_frends:
			if (AppBasic.isLogin) {
				startActivity(new Intent(getApplicationContext(), RecommendListActivity.class));
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.side_layout_security_center:
			if (AppBasic.isLogin) {
				startActivity(new Intent(getApplicationContext(), SecurityCenterActivity.class));
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.side_btn_logout:
			if (AppBasic.isLogin) {
				onRequest(LOGINOUT, UrlConstant.LOGOUT, HttpMethod.POST, null);
			} else {
				startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
						LOGIN);
			}
			break;
		case R.id.gesturepwd_unlock_forget:
			startActivityForResult(new Intent(MainActivity.this, LoginActivity.class),
					REQUEST_CODE_Gesturepwd_Unlock_Forget);
			break;
		case R.id.btn_guide_recommend:
			recommendGuide.setVisibility(View.GONE);
			PreferencesUtils.putBoolean(MainActivity.this,
					PreferencesUtils.getIsFirstRecommend(this), false);
			break;
		case R.id.assets_guide:
			assetsGuide.setVisibility(View.GONE);
			PreferencesUtils.putBoolean(MainActivity.this, PreferencesUtils.getIsFirstAssets(this),
					false);
			break;
		case R.id.side_layout_sina:
			if (!isFastDoubleClick()) {   // 添加防重复判断
				if (AppBasic.isLogin) {
					onRequest(SINA_ACCOUNT, UrlConstant.SINA_ACCOUNT, HttpMethod.GET, null);
				} else {
					startActivityForResult(new Intent(getApplicationContext(), LoginActivity.class),
							LOGIN);
				}
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		sharedPreferences = getSharedPreferences("test", Activity.MODE_PRIVATE);
		editor = sharedPreferences.edit();

		mFragmentManager = getSupportFragmentManager();
		/*set the shadow for drawer at start(left) or end(right)*/
		mDrawerLayout.setDrawerShadow(R.drawable.home_bulletin_bar_bg,
				GravityCompat.START);

		/*set the application ActionBar title changes*/
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ind_icon_woh, R.string.drawer_open,
				R.string.drawer_close) {
			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				/* 这里设置clickable(true)	必须动态设置，静态设置没有效果
				 * 解决问题	侧滑菜单出来的时候，点击菜单上的区域会有点击穿透的问题
				 */
				mSideLayout.setClickable(true);		

				getUserInfo();
				if (AppBasic.isLogin) {
					setData();
					logoutLayout.setVisibility(View.VISIBLE);
				} else {
					logoutLayout.setVisibility(View.INVISIBLE);
				}
				setClickTrue();
				PreferencesUtils.putBoolean(getApplicationContext(), "isFirstDragLayout", false);
			}

			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
				setClickFalse();
				PreferencesUtils.putBoolean(getApplicationContext(), "isFirstDragLayout", true);
			}
		};
		/*set the DrawerLayout Listener*/
		mDrawerLayout.setDrawerListener(mDrawerToggle);


		// 手势解锁
		mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);
		if (AppBasic.getInstance().getLockPatternUtils().savedPatternExists()) {
			mGesturePassword.setVisibility(View.VISIBLE);
		}

		if (PreferencesUtils.getBoolean(this, PreferencesUtils.getIsFirstRecommend(this), true)) {
			recommendGuide.setVisibility(View.VISIBLE);
		}

		mHomeTabRecommendationLayout.setOnClickListener(this);
		mHomeTabAssetsLayout.setOnClickListener(this);
		mHomeTabInvestmentLayout.setOnClickListener(this);
		mHomeTabMoreLayout.setOnClickListener(this);

		setTabSelection(0);

		setRating();
		
		initBitmapUtils();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		/*make sure the home icon enable click and display the DrawerLayout*/
		if (mDrawerToggle.onOptionsItemSelected(item)){
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume() {
		super.onResume();
		boolean isFirstDragLayout = PreferencesUtils.getBoolean(getApplicationContext(),
				"isFirstDragLayout", true);
		if (isFirstDragLayout) {
			setClickFalse();
		} else {
			setClickTrue();
		}

		getUserInfo();

		setRating();
		getPushInfo();
	}

	private void setClickFalse() {
		member_center.setClickable(false);
		giftLayout.setClickable(false);
		pointsLayout.setClickable(false);
		shopLayout.setClickable(false);
		msgLayout.setClickable(false);
		frendsLayout.setClickable(false);
		securityLayout.setClickable(false);
		logoutLayout.setClickable(false);
		unLoginLayout.setClickable(false);
		loginLayout.setClickable(false);
		mBtnRegedit.setClickable(false);
		icon.setClickable(false);
		mBtnLogin.setClickable(false);

	}

	private void setClickTrue() {
		member_center.setClickable(true);
		giftLayout.setClickable(true);
		pointsLayout.setClickable(true);
		shopLayout.setClickable(true);
		msgLayout.setClickable(true);
		frendsLayout.setClickable(true);
		securityLayout.setClickable(true);
		logoutLayout.setClickable(true);
		unLoginLayout.setClickable(true);
		loginLayout.setClickable(true);
		mBtnRegedit.setClickable(true);
		icon.setClickable(true);
		mBtnLogin.setClickable(true);

	}

	/**
	 *会员等级图标更新 
	 */
	public void setRating(){
		if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("0")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v0);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("1")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v1);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("2")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v2);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("3")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v3);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("4")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v4);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("5")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v5);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("6")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v6);
		} else if (AppBasic.memberRating !=null && AppBasic.memberRating.equals("7")) {
			ge_icon_vip.setImageResource(R.drawable.ge_icon_v7);
		}
	}

	protected void setData() {
		tv_security_string.setVisibility(View.VISIBLE);
		if (AppBasic.unReadMessageCount > 0) {
			mTvMessages.setText(AppBasic.unReadMessageCount + "");
			mTvMessages.setVisibility(View.VISIBLE);
		} else {
			mTvMessages.setVisibility(View.GONE);
		}

		setRating();

		if (!TextUtils.isEmpty(AppBasic.securityLevel) && AppBasic.isLogin) {
			mTvSecurity.setVisibility(View.VISIBLE);
			if ("Low".equals(AppBasic.securityLevel)) {
				mTvSecurity.setText("[低]");
				mTvSecurity.setTextColor(getResources().getColor(R.color.home_rate_color));
			} else if ("Medium".equals(AppBasic.securityLevel)) {
				mTvSecurity.setText("[中]");
				mTvSecurity.setTextColor(getResources().getColor(R.color.home_shf_text));
			} else if ("High".equals(AppBasic.securityLevel)) {
				mTvSecurity.setText("[高]");
				mTvSecurity.setTextColor(getResources().getColor(R.color.home_phb_text));
			}
		} else {
			mTvSecurity.setVisibility(View.INVISIBLE);
		}

		unLoginLayout.setVisibility(View.GONE);
		loginLayout.setVisibility(View.VISIBLE);
		mBtnLogout.setVisibility(View.VISIBLE);

		mTvName.setText(AppBasic.username + "（" + AppBasic.nickname + "）");
		mTvInvestmentCode.setText("邀请码：" + AppBasic.urlToken);
		if (!TextUtils.isEmpty(AppBasic.avatar)) {
			AppBasic.getBitmapUtils(MainActivity.this).display(icon, AppBasic.avatar);
		}

	}

	protected void getUserInfo() {
		if(AppBasic.isLogin) {
			onRequest(USERINFO, UrlConstant.GETMYINFO, HttpMethod.GET, null);
		}
	}
	
	protected void getPushInfo() {
		if(AppBasic.isLogin) {
			onRequest(GET_PUSH_INFO, UrlConstant.GETPUSHINFO, HttpMethod.GET, null);		
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);

		toWhere = getIntent().getStringExtra("key");
		if (!TextUtils.isEmpty(toWhere)) {
			if ("investment".equals(toWhere)) {
				setTabSelection(1);
			} 
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.home_tab_recommendation_layout:
			setTabSelection(0);
			break;
		case R.id.home_tab_investment_layout:
			setTabSelection(1);
			break;
		case R.id.home_tab_assets_layout:
			if (!AppBasic.isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			setTabSelection(2);
			break;
		case R.id.home_tab_more_layout:
			setTabSelection(3);
			break;
		case R.id.call_server:
			dialog.dismiss();

			if (AppBasic.app != null && !TextUtils.isEmpty(AppBasic.app.serviceTel)) {
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ AppBasic.app.serviceTel));
				startActivity(intent);
			} else {
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:400-969-1688"));
				startActivity(intent);
			}
			break;
		case R.id.company_server:
			dialog.dismiss();
			Utils.openSession(this, Constants.QQ_PACKAGENAME, Constants.MARKETING_QQ);
			break;
		case R.id.qq_server:
			dialog.dismiss();

			if (!TextUtils.isEmpty(AppBasic.bindQQ)) {
				Utils.openSession(this, Constants.QQ_PACKAGENAME, AppBasic.bindQQ);
			}
			Utils.openSession(this, Constants.QQ_PACKAGENAME, Constants.MARKETING_QQ);
			break;

		default:
			break;
		}
	}


	/**
	 * Tab选中状态
	 * 
	 * @param index
	 */
	private void setTabSelection(int index) {
		// 设置选中状态显示当前内容视图
		//		mTabHost.setCurrentTab(index);
		if (index == 0) {
			titleLogo.setVisibility(View.GONE);
			home_title_string.setVisibility(View.GONE);
			// home_title.setBackground(null);
			home_title.setBackgroundDrawable(null);
			investmentLayot.setVisibility(View.GONE);
			setMargins(realtabcontent, 0, 0, 0, 0);
			home_left.setImageResource(R.drawable.tui_icon_wo);
			home_right.setImageResource(R.drawable.tui_icon_kef);
		}else if(index == 1 ){
			titleLogo.setVisibility(View.GONE);
			home_title_string.setVisibility(View.GONE);
			investmentLayot.setVisibility(View.VISIBLE);
			// home_title.setBackground(getResources().getDrawable(R.drawable.home_bulletin_bar_bg));
			home_title.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.home_bulletin_bar_bg));
			int top = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 44,
					getResources().getDisplayMetrics());
			setMargins(realtabcontent, 0, top, 0, 0);
			home_left.setImageResource(R.drawable.ind_icon_woh);
			home_right.setImageResource(R.drawable.ind_icon_kefh);
		}else {
			titleLogo.setVisibility(View.GONE);
			home_title_string.setVisibility(View.VISIBLE);
			// home_title.setBackground(getResources().getDrawable(R.drawable.home_bulletin_bar_bg));
			investmentLayot.setVisibility(View.GONE);
			home_title.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.home_bulletin_bar_bg));
			int top = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 44,
					getResources().getDisplayMetrics());
			setMargins(realtabcontent, 0, top, 0, 0);
			home_left.setImageResource(R.drawable.ind_icon_woh);
			home_right.setImageResource(R.drawable.ind_icon_kefh);
		}
		home_title_string.setText(titleArray[index]);
		//		int count = mTabHost.getTabWidget().getChildCount();
		for (int i = 0; i < imgIds.length; i++) {
			if (i == index) {
				((ImageView) findViewById(imgIds[i]))
				.setImageResource(iconPressed[i]);
				((TextView) findViewById(txtIds[i])).setTextColor(getResources()
						.getColor(R.color.home_tab_text_pressed));
			} else {
				((ImageView) findViewById(imgIds[i]))
				.setImageResource(iconNormal[i]);
				((TextView) findViewById(txtIds[i])).setTextColor(getResources()
						.getColor(R.color.home_tab_text_normal));
			}
		}


		FragmentTransaction transaction = mFragmentManager.beginTransaction();

		hideFragments(transaction);
		switch (index) {
		case 0:
			if (recommendationFragment == null) {
				recommendationFragment = new RecommendationFragment();
				transaction.add(R.id.realtabcontent, recommendationFragment);
			} else {
				transaction.show(recommendationFragment);
			}
			break;
		case 1:

			if (AppBasic.isShow) {
				if (investmentFragment == null) {
					investmentFragment = new InvestmentFragment();
					transaction.add(R.id.realtabcontent, investmentFragment);
				} else {
					transaction.show(investmentFragment);
				}
			} else {
				if (investmentBillFragment == null) {
					investmentBillFragment = new InvestmentBillFragment();
					transaction.add(R.id.realtabcontent, investmentBillFragment);
				} else {
					transaction.show(investmentBillFragment);
				}
			}

			break;

		case 2:
			if (assetsFragment == null) {
				assetsFragment = new AssetsFragment();
				transaction.add(R.id.realtabcontent, assetsFragment);
			} else {
				transaction.show(assetsFragment);
			}
			break;

		case 3:
			if (moreFragment == null) {
				moreFragment = new MoreFragment();
				transaction.add(R.id.realtabcontent, moreFragment);
			} else {
				transaction.show(moreFragment);
			}
			break;
		default:
			break;
		}
		transaction.commitAllowingStateLoss();

		if (index == 0) {
			Intent intent = new Intent("isDrag");
			intent.putExtra("isDrag", false);
			sendBroadcast(intent);
		}

		if (index == 2) {
			if (PreferencesUtils.getBoolean(this, PreferencesUtils.getIsFirstAssets(this), true)) {
				assetsGuide.setVisibility(View.VISIBLE);
			}
		}

	}

	private void hideFragments(FragmentTransaction transaction) {
		if(recommendationFragment != null) {
			transaction.hide(recommendationFragment);
		}
		if(investmentFragment != null) {
			transaction.hide(investmentFragment);
		}
		if (investmentBillFragment != null) {
			transaction.hide(investmentBillFragment);
		}
		if(assetsFragment != null) {
			transaction.hide(assetsFragment);
		}
		if(moreFragment != null) {
			transaction.hide(moreFragment);
		}

	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case LOGINOUT:
			logOut();
			break;
		case USERINFO:
			java.lang.reflect.Type type1 = new TypeToken<User>() {
			}.getType();
			User user = gson.fromJson(result, type1);

			AppBasic.isCheckIned = user.isCheckIned;
			AppBasic.totalScore = user.score;
			AppBasic.certNo = user.certNo;
			AppBasic.realName = user.realName;
			AppBasic.avatar = user.avatar;
			AppBasic.username = user.username;
			AppBasic.nickname = user.nickname;
			AppBasic.urlToken = user.urlToken;
			AppBasic.securityLevel = user.securityLevel;
			AppBasic.isSetSecurityCode = user.isSetSecurityCode;
			AppBasic.tel = user.tel;
			AppBasic.email = user.email;
			AppBasic.isVerifiedEmail = user.isVerifiedEmail;
			AppBasic.isSetSecurityQuestion = user.isSetSecurityQuestion;
			AppBasic.unReadMessageCount = user.unReadMessageCount;
			AppBasic.rewardScore = user.rewardScore;
			AppBasic.nextTimeScore = user.nextTimeScore;
			AppBasic.bindQQ = user.bindQQ;
			AppBasic.haveNewHotActivity = user.haveNewHotActivity;
			AppBasic.haveNewArticel = user.haveNewArticel;
			AppBasic.birthday = user.birthday;
			AppBasic.isSetSinaPayPassword = user.isSetSinaPayPassword;
			AppBasic.memberRating = user.memberRating;
			AppBasic.memberRank = user.memberRank;

			setRating();
			if (recommendationFragment != null && recommendationFragment.isVisible()) {
				recommendationFragment.onResume();
			}
			break;
		case CHANGEAVATAR:
			java.lang.reflect.Type type = new TypeToken<Avatar>() {
			}.getType();
			Avatar avatar = gson.fromJson(result, type);
			if (avatar != null && !TextUtils.isEmpty(avatar.avatarUrl)) {
				AppBasic.avatar = avatar.avatarUrl;
				AppBasic.getBitmapUtils(MainActivity.this).display(icon, AppBasic.avatar);
			}
			break;
		case CHANGENICKNAME:
			mTvName.setText(AppBasic.username + "(" + AppBasic.nickname + ")");
			mTvName.setCompoundDrawables(null, null, null, null);
			mTvName.setOnClickListener(null);
			break;
		case SINA_ACCOUNT:
			java.lang.reflect.Type type4 = new TypeToken<SinaDetail>() {}.getType();
			SinaDetail detail = gson.fromJson(result, type4);
			if (null == detail) return;

			if (detail.code.equalsIgnoreCase("APPLY_SUCCESS")) {
				Utils.jumpURL(this, detail.message, "新浪账户", "", false);
			}
			break;
		case GET_PUSH_INFO:
			java.lang.reflect.Type type5 = new TypeToken<GetPushInfo>() {}.getType();
			GetPushInfo pushinfo = gson.fromJson(result, type5);
			
			if (null == pushinfo || !pushinfo.isShow) return;
			
			if (pushinfo.isShow) {
				showDialog(pushinfo);
			}
			break;
		default:
			break;
		}
	}
	
	private void showDialog (final GetPushInfo pushinfo) {
		alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.show();
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.dialog_main);

		close = (ImageView) window.findViewById(R.id.close);
		birthday_push = (ImageView) window.findViewById(R.id.birthday_push);
		
		setImageBitmap(birthday_push, pushinfo.image);
		
		close.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				alertDialog.cancel();
			}
		});
		birthday_push.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Utils.jumpURL(MainActivity.this, pushinfo.url, pushinfo.title, "", false);
				alertDialog.cancel();
			}
		});
//		PreferencesUtils.putBoolean(MainActivity.this, PreferencesUtils.getIsFirstBirthday(this),
//				false);
		
	}
	
	BitmapUtils bitmapUtils;
	BitmapDisplayConfig displayConfig;
	
	private void initBitmapUtils() {
		bitmapUtils = new BitmapUtils(this);
		displayConfig = new BitmapDisplayConfig();
		displayConfig.setShowOriginal(false);
		displayConfig.setBitmapMaxSize(BitmapCommonUtils.getScreenSize(this));
	}
	
	/**
	 * 加载图片
	 * 
	 */
	
	private void setImageBitmap(ImageView view, String url) {
		if (!TextUtils.isEmpty(url)) {
			Bitmap bmp = bitmapUtils.getBitmapFromMemCache(url, displayConfig);
			if (bmp != null) {
				view.setImageBitmap(bmp);
			} else {
				bitmapUtils.display(view, url, displayConfig);
			}
			view.setVisibility(View.VISIBLE);
		} else {
			view.setImageBitmap(null);
		}
	}

	private void logOut() {
		AppBasic.isLogin = false;
		editor.putString("data", ""); //清空本地购物车信息
		editor.commit();
		editor.putString("address", ""); // 清空本地存储地址信息
		editor.commit();
		MyToast.showHMToast(this, true, "退出登录成功");
		PreferencesUtils.putString(this, PreferencesUtils.USER_PHONE, "");
		PreferencesUtils.putString(this, PreferencesUtils.USER_PASSWORD, "");

		loginLayout.setVisibility(View.INVISIBLE);
		mBtnLogout.setVisibility(View.GONE);
		unLoginLayout.setVisibility(View.VISIBLE);
		icon.setImageResource(R.drawable.ind_icon_toux);
		mTvMessages.setVisibility(View.INVISIBLE);
		mTvSecurity.setText("");
		tv_security_string.setVisibility(View.GONE);
		mPhotoGraph = null;
		ge_icon_vip.setVisibility(View.GONE);

		Intent intent1 = new Intent("isAnim");
		intent1.putExtra("isAnim", false);
		sendBroadcast(intent1);
	}

	@Override
	public void onPostFailure(int postId, String msg) {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == LOGIN && resultCode == RESULT_OK) {
			setData();
			ge_icon_vip.setVisibility(View.VISIBLE);
			setRating();
		} else if (requestCode == REQUEST_CODE_Gesturepwd_Unlock_Forget && resultCode == RESULT_OK
				&& data != null && data.getBooleanExtra("loginSuccess", false)) {
			mGesturePassword.setVisibility(View.GONE);
			AppBasic.getInstance().getLockPatternUtils().clearLock();
		}

		if (mPhotoGraph != null) {
			mPhotoGraph.onActivityResult(requestCode, resultCode, data);
		}
	}

	@Override
	public void onSucess(String mPath) {

		if (!TextUtils.isEmpty(mPath)) {
			try {
				RequestParams params = new RequestParams();
				params.addBodyParameter("avatar", new File(mPath));
				onRequest(CHANGEAVATAR, UrlConstant.CHANGEAVATAR, HttpMethod.POST, params);
			} catch (Exception e) {

			}
		}

	}

	@Override
	public void onError(String mError) {

	}

	@Override
	public void onCancel() {

	}

	@Override
	public void onBackPressed() {
		backSystem();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mCountdownTimer != null)
			mCountdownTimer.cancel();
		
		if (alertDialog !=null && alertDialog.isShowing()) {
			alertDialog.cancel();
			alertDialog = null;
		}
	}

	EasyDialog dialog;

	/**
	 * 显示提示信息
	 */
	/**
	 * 显示客服服务信息
	 */
	private void showKFServer() {
		View root = LayoutInflater.from(this).inflate(R.layout.dialog_custom_server, null);

		root.findViewById(R.id.call_server).setOnClickListener(this);
		root.findViewById(R.id.company_server).setOnClickListener(this);
		root.findViewById(R.id.qq_server).setOnClickListener(this);
		root.setBackgroundColor(getResources().getColor(R.color.tran));

		dialog = new EasyDialog(this).setLayout(root) // 设置布局文件
				.setBackgroundColor(getResources().getColor(R.color.tran)) // 设置布局背景
				.setLocationByAttachedView(home_right) // 设置显示位置
				.setTouchOutsideDismiss(true) // 设置触摸外部是否取消
				.setMatchParent(false) // 设置是否填充
				.setMarginLeftAndRight(2, 0) // 距离屏幕位置
				.setOutsideColor(Color.TRANSPARENT) // 设置对话框外部背景颜色
				.setMarginLeftAndRight(0, 0)
				.show();
	}

	/*
	 * 设置Margin 
	 */
	public static void setMargins (View v, int l, int t, int r, int b) {
		if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
			ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
			p.setMargins(l, t, r, b);
			v.requestLayout();
		}
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};

	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<LockPatternView.Cell> pattern) {
			if (pattern == null)
				return;
			if (AppBasic.getInstance().getLockPatternUtils().checkPattern(pattern)) {
				mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);

				mGesturepwdUnlockFace.setBackgroundResource(R.anim.suo_dui_animation);
				((AnimationDrawable) mGesturepwdUnlockFace.getBackground()).stop();
				((AnimationDrawable) mGesturepwdUnlockFace.getBackground()).start();

				int duration = 0;
				for (int i = 0; i < ((AnimationDrawable) mGesturepwdUnlockFace.getBackground())
						.getNumberOfFrames(); i++) {
					duration += ((AnimationDrawable) mGesturepwdUnlockFace.getBackground())
							.getDuration(i);
				}

				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {
					public void run() {
						mGesturePassword.setVisibility(View.GONE);
					}
				}, duration);

			} else {
				mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
				if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
					mFailedPatternAttemptsSinceLastTimeout++;
					int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT
							- mFailedPatternAttemptsSinceLastTimeout;
					if (retry >= 0) {
						if (retry == 0)
							MyToast.showHMToast(MainActivity.this, false, "您已5次输错密码，请30秒后再试");
						mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
						mHeadTextView.setTextColor(Color.RED);
						mHeadTextView.startAnimation(mShakeAnim);

						mGesturepwdUnlockFace.setBackgroundResource(R.anim.suo_cuo_animation);
						((AnimationDrawable) mGesturepwdUnlockFace.getBackground()).stop();
						((AnimationDrawable) mGesturepwdUnlockFace.getBackground()).start();
					}

				} else {
					MyToast.showHMToast(MainActivity.this, false, "输入长度不够，请重试");
				}

				if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
					mHandler.postDelayed(attemptLockout, 2000);
				} else {
					mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
				}
			}
		}

		public void onPatternCellAdded(List<Cell> pattern) {

		}

		private void patternInProgress() {
		}
	};

	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			mLockPatternView.clearPattern();
			mLockPatternView.setEnabled(false);
			mCountdownTimer = new CountDownTimer(LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1,
					1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					if (secondsRemaining > 0) {
						mHeadTextView.setText(secondsRemaining + " 秒后重试");
					} else {
						mHeadTextView.setText("请绘制手势密码");
						mHeadTextView.setTextColor(Color.WHITE);
					}

				}

				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
				}
			}.start();
		}
	};

	protected static long lastClickTime;

	/** 防止在短时间重复点击 **/
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 5000) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
}
